<?php
/**
 * Create By: PhpStorm
 * User: niechenguang
 * File: Circle.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\note;

use app\api\model\dao\ConsumerRank;
use app\api\model\dao\DashangGift;
use app\api\model\dao\DashangRecord;
use app\api\model\dao\Note;
use app\api\model\dao\Circle;
use app\api\model\dao\UpRank;
use app\api\model\dao\UserCurrency;
use app\api\model\data\currency\ConsumeCurrency;
use app\library\Error;
use app\library\Flag;
use app\library\PageBase;
use think\Exception;
use think\Log;
use think\Validate;

class NoteReward extends PageBase
{

    private $objNote;
    private $objCircle;
    private $objDashangGift;
    private $objDashangRecord;
    private $objUpRank;
    private $objCurrency;
    private $objConsumeCurrency;
    private $objConsumerRank;

    public function __construct()
    {
        parent::__construct();

        $this->objNote = new Note();
        $this->objCircle = new Circle();
        $this->objDashangGift = new DashangGift();
        $this->objDashangRecord = new DashangRecord();
        $this->objUpRank = new UpRank();
        $this->objCurrency = new UserCurrency();
        $this->objConsumeCurrency = new ConsumeCurrency();
        $this->objConsumerRank = new ConsumerRank();
    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'note_id' => 'require',
            'gift_id' => 'require',
        ];
        $msg = [
            'note_id.require' => '帖子id不能为空',
            'gift_id.require' => '请选择打赏的礼物',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    public function excute($param)
    {
        $ret = $this->checkToken($param);
        if (false === $ret) {
            return $this->getRes(Error::ERR_NO_AUTH);
        }


        // 1、参数校验
        $ret = $this->checkParam($param);
        if ($ret) {
            return $this->getRes(Error::ERR_PARAM);
        }

        // 2、从数据库中获取帖子详情
        $ret = $this->getNoteInfoFromDB($param['note_id']);
        if (false === $ret) {
            return $this->getRes(Error::ERR_SYS, 'get note info from db fail. [note_id: ' . $param['note_id'] . ']');
        }


        if (empty($ret)) {
            return $this->getRes(Error::ERR_NOTE_NOT_EXIST);
        }

        // 3、校验是否被删除
        if (Flag::CONST_NOTE_DELETED == $ret['is_delete']) {
            return $this->getRes(Error::ERR_NOTE_DELETED);
        }

        // 不能打赏给自己
        if ($ret['creator'] == $this->user_id) {
            return $this->getRes(Error::ERR_NOTE_REWARD_NOT_MINE);
        }

        // 4、获取礼物信息
        $gift = $this->getGiftFromDB($param['gift_id']);
        if (false === $gift) {
            return $this->getRes(Error::ERR_SYS, 'get dashang gift info from db fail. [gift_id: ' . $param['gift_id'] . ']');
        }

        if (empty($gift)) {
            return $this->getRes(Error::ERR_DASHANG_GIFT_NOT_EXIST);
        }

        // 3、打赏礼物是否已下架
        if (Flag::CONST_DASHANGGIFT_DOWN == $gift['up']) {
            //throw new Exception('dashang gift is down', Error::ERR_DASHANG_GIFT_DOWN);
        }

        // 漫币数是否足够
        $user_currency = $this->objCurrency->getCurrencyByUserid($this->user_id, Flag::CURRENCY_TYPE_COIN);
        if (empty($user_currency) || $user_currency['amount'] < $gift['money']) {
            return $this->getRes(Error::ERR_USER_CURRENCY_NOT_ENOUGH);
        }

        $date = date('Ymd');

        // 5、构造打赏参数
        $input = [
            'category_id' => $ret['category_id'],
            'cir_id' => $ret['cir_id'],
            'note_id' => trim($param['note_id']),
            'userid' => $this->user_id,
            'note_userid' => $ret['creator'],
            'gift_id' => $gift['id'],
            'gift_name' => $gift['name'],
            'money' => $gift['money'],
            'popularity' => $gift['popularity'],
            'date' => $date,
            'update_time' => time(),
            'create_time' => time(),
        ];

        $add_ret = $this->objDashangRecord->addDashangRecord($input);
        if (false === $add_ret) {
            return $this->getRes(Error::ERR_SYS, 'add dashang record fail...[input: ' . json_encode($input) . ']');
        }

        // 扣除漫币和增加漫币
        //$deduct_currency_ret = $this->objCurrency->deductCurrency($this->user_id, Flag::CURRENCY_TYPE_COIN, $gift['money']);
        //if (false === $deduct_currency_ret) {
        //throw new Exception('deduct currency fail. [userid:' . $this->user_id . '][money:' . $gift['money'] . ']', Error::ERR_SYS);
        //}
        //$add_currency_ret = $this->objCurrency->addCurrency($ret['creator'], Flag::CURRENCY_TYPE_COIN, $gift['money']);
        $add_currency_ret = $this->objConsumeCurrency->consumeCurrency($ret['creator'], $this->user_id, $gift['money'], Flag::CURRENCY_TYPE_COIN, Flag::CURRENCY_EXCHANGE_TYPE_DASHANG);
        if (false === $add_currency_ret) {
            return $this->getRes(Error::ERR_SYS, 'add currency fail. [userid:' . $this->user_id . '][money:' . $gift['money'] . ']');
        }

        // 增加消费值
        $consumer_rank_ret = $this->objConsumerRank->plusConsumer($this->user_id, $date, $gift['money']);
        if (false === $consumer_rank_ret) {
            Log::error(' add consumer rank fail. [userid:' . $this->user_id . '][date:' . $date . '][money:' . $gift['money'] . ']');
        }

        // 人气值增加
        $up_rank_ret = $this->objUpRank->plusUp($ret['creator'], $date);
        if (false === $up_rank_ret) {
            Log::error(' add consumer rank fail. [userid:' . $ret['creator'] . '][date:' . $date . ']');
        }

        $this->data['mine_money'] = strval($user_currency['amount'] - $gift['money']);

        return $this->getRes();
    }

    /**
     * 从数据库中获取帖子详情
     *
     * @param $cir_id
     * @return bool|false|\PDOStatement|string|\think\Collection
     */
    public function getNoteInfoFromDB($note_id)
    {
        if (!$note_id) {
            return false;
        }
        $arrCond = [
            'id' => ['=', $note_id]
        ];
        $ret = $this->objNote->getNote($arrCond);
        if (false === $ret) {
            return false;
        }
        if (empty($ret)) {
            return [];
        }
        $ret = $ret[0];
        return $ret;
    }

    /**
     * 从数据库中获取打赏礼物
     *
     * @param $cir_id
     * @return bool|false|\PDOStatement|string|\think\Collection
     */
    public function getGiftFromDB($gift_id)
    {
        if (!$gift_id) {
            return false;
        }
        $arrCond = [
            'id' => ['=', $gift_id]
        ];
        $ret = $this->objDashangGift->getDashangGift($arrCond);
        if (false === $ret) {
            return false;
        }
        if (empty($ret)) {
            return [];
        }
        $ret = $ret[0];
        return $ret;
    }
}
